package com.mini.demos.webgame.handler;

import java.math.BigDecimal;

import com.mini.demos.webgame.cache.CacheManager;
import com.mini.demos.webgame.db.JobService;
import com.mini.demos.webgame.entity.User;
import com.mini.demos.webgame.msg.JobMsg;
import com.mini.demos.webgame.msg.JobMsgResp;
import com.mini.demos.webgame.msg.MsgHead;
import com.mini.demos.webgame.queue.JobQueue;
import com.mini.demos.webgame.util.CommandConstants;
import com.mini.demos.webgame.util.MsgSequenceId;
import com.mini.demos.webgame.util.Utils;
import com.mini.framework.communicate.mina.handler.Handler;
import com.mini.framework.communicate.mina.protocol.Msg;

public class JobHandler extends Handler {

	@Override
	public void handle(Msg msg) {
		JobMsg jobMsg = (JobMsg) msg;
		JobQueue jobQueue = JobQueue.getInstance();
		User user = CacheManager.getInstance().getUserCache(jobMsg.getUserName());
		Float mm = user.getMoney();
		synchronized(user){
			Float money = user.getMoney();
			BigDecimal m = new BigDecimal(money).subtract(new BigDecimal(jobMsg.getCostPrice()));
			mm = m.floatValue();
			user.setMoney(mm);
			CacheManager.getInstance().putUserCache(user);
		}
		new JobService().saveJob(jobMsg);//保存job.
		jobQueue.addJob(jobMsg);
		
		JobMsgResp jobMsgResp = new JobMsgResp();
		jobMsgResp.setCode(0);
		jobMsgResp.setMoney(mm);
		jobMsgResp.setCodeMsg("");

		MsgHead head = new MsgHead();
		head.setVersion((byte) 0x01);
		head.setCommandId(CommandConstants.JOB_RESP);
		head.setSeqId(MsgSequenceId.getInstance().getSequenceId());
		Integer totalLength = CommandConstants.HEAD_LENGTH
				+ jobMsgResp.getBodyLength();
		head.setTotalLength(totalLength.intValue());
		head.setTime(Utils.getTime());
		head.setSpace(0);
		jobMsgResp.setHead(head);
		msg.getSender().send(jobMsgResp);

	}
	
	

}
